//
//  MA.swift
//  GomroClient
//
//  Created by xiaogxjkz on 2021/4/19.
//  Copyright © 2021 cn.gomro.app. All rights reserved.
//

import Foundation

/// MA 简单移动平均线(Moving Average)
/// 参考：https://blog.csdn.net/yuhk231/article/details/80810252?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161880799416780366574685%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=161880799416780366574685&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~baidu_landing_v2~default-6-80810252.nonecase&utm_term=K%E7%BA%BF%E6%8A%80%E6%9C%AF%E6%8C%87%E6%A0%87
struct MA {
    
    enum kpiType:String {
        case ma5 = "MA5"
        case ma10 = "MA10"
        case ma15 = "MA15"
        case ma20 = "MA20"
        case ma30 = "MA30"
        case ma40 = "MA40"
        case ma60 = "MA60"
    }
    
    
    /// 计算MA均线
    /// - Parameters:
    ///   - d: 数据源
    ///   - n: MA时间窗口 5,10,20,60
    ///   - f: 计算字段
    /// - Returns: [Double]
    static func calcMA(Data d:[Any],
                       andNmbner n:Int,
                       withFiled f:String? = "Close") -> [Double] {
        
        var sum = Double.zero
        var maArr = [Double]()
        
        if f != nil && f != "" {
            for i in 0..<d.count {
                if i < n - 1 {
                    continue
                }
                
                sum = 0
                for j in 0..<n {
                    if let _item = d[i-j] as? [String:Any] {
                        let _temp = Double("\(_item[f!] ?? 0.0)")!
                        sum += _temp
                    }
                }
                
                maArr.append(sum/Double(n))
            }
        }
        
        return maArr
    }
    
    static func calcMA(Model d:[GameMarketModel],
                       andNmbner n:Int) -> [Double] {
        
        var sum = Double.zero
        var maArr = [Double]()
        
        for i in 0..<d.count {
            if i < n - 1 {
                //maArr.append(Double.zero)
                continue
            }
            
            sum = 0
            for j in 0..<n {
                let _item = d[i-j]
                let _temp = Double(_item.close ?? "0.0")!
                sum += _temp
            }
            
            maArr.append(sum/Double(n))
        }
        
        return maArr
    }
}
